package com.micrometa.km.ui.components.tree;

import java.awt.Component;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JTree;
import javax.swing.filechooser.FileSystemView;

import org.pushingpixels.substance.api.renderers.SubstanceDefaultTreeCellRenderer;

public class FileTreeCellRenderer extends SubstanceDefaultTreeCellRenderer{
	private static final long serialVersionUID = 1L;
	public static FileSystemView fsv = FileSystemView.getFileSystemView();
	private Map<String, Icon> iconCache = new HashMap<String, Icon>();
	private Map<File, String> rootNameCache = new HashMap<File, String>();

	@Override
	public Component getTreeCellRendererComponent(JTree tree, Object value,
			boolean sel, boolean expanded, boolean leaf, int row,
			boolean hasFocus) {
		FileTreeNode ftn = (FileTreeNode) value;
		File file = ftn.getFile();
		String filename = "";
		if (file != null) {
			if (!file.isDirectory()) {
				filename = rootNameCache.get(file);
				if (filename == null) {
					filename = fsv.getSystemDisplayName(file);
					rootNameCache.put(file, filename);
				}
			} else {
				filename = file.getName();
			}
		}
		JLabel result = (JLabel) super.getTreeCellRendererComponent(tree,
				filename, sel, expanded, leaf, row, hasFocus);
		if (file != null) {
			Icon icon = iconCache.get(filename);
			if (icon == null) {
				icon = ftn.getIcon();
				iconCache.put(filename, icon);
			}
			result.setIcon(icon);
		}
		return result;
	}
}
